/*******************************************************************************
 * This file is part of blueprint4j www.blueprint4j.org.
 * 
 *     blueprint4j is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     blueprint4j is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with blueprint4j. If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package blueprint4j.report;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;

import javax.swing.JButton;
import javax.swing.JDialog;

import blueprint4j.db.DBConnection;
import blueprint4j.utils.BindException;
import blueprint4j.utils.Bindable;
import blueprint4j.utils.BindableProperties;
import blueprint4j.utils.Log;
import blueprint4j.utils.VectorBindable;

/**
 * This class serves as an interface between entities and building the rport
 * Database, and fields are binded using the following protocol
 * database and field are seperated by a double under score [__]
 */

public class Report implements ActionListener{
    
    private JButton proceed = null;
    private DBConnection connection = null;
    private String resource_name = null;
    private VectorBindable bindable = null;
 //   private Binder binder = null;
    private Hashtable bind_map = null;
    private BindableProperties bindable_properties = null;
  //  private JasperPrint print = null;
  //  private JasperReport report = null;
    private JDialog dialog = null;
    private Hashtable extra_properties = new Hashtable();
    
    /**
     * resource_name - the name of the resource (jasper report file)
     * bindable - the list of entities
     */
    public Report(DBConnection connection,String resource_name,VectorBindable bindable)
    throws BindException {
        this.connection = connection;
        this.resource_name = resource_name;
        this.bindable = bindable;
    }
    
    public Report(DBConnection connection,String resource_name,VectorBindable bindable,Hashtable extra_properties)
    throws BindException {
        this(connection,resource_name,bindable);
        this.extra_properties = extra_properties;
    }
    
    public void build()
    throws BindException {
        try {
//            java.net.URL url = ClassLoader.getSystemResource(resource_name);
//            if (url == null) {
//                throw new BindException("COUNT NOT LOCATE REPORT CALLED ["+resource_name+"]");
//            }
//            report = JasperManager.loadReport(url.openStream());
//            VectorJRParameter field = new VectorJRParameter(report.getParameters());
//            bind_map = field.bindMap(bindable);
//            if (extra_properties != null){
//                field.bindCommon(extra_properties);
//                bind_map.putAll(extra_properties);
//            }
//            
//            bindable_properties = new BindableProperties();
//            binder = new Binder();
//            BindFieldInterface[] bind_field = field.getAllNonBindedField(bindable,bindable_properties);
//            if (bind_field != null && bind_field.length > 0) {
//                System.out.println("Enter required fields");
//                DataGroup report_group = new DataGroup("Enter required fields");
//                binder.addBindable(bindable_properties);
//                for (int i =0;i < bind_field.length;i++) {
//                    // SET A DEFAULT
//                    DataPair dp = binder.createDataPair(bind_field[i]);
//                    if (dp instanceof DataPairFieldDate) {
//                        ((BindDateInterface)((DataPairFieldDate)dp).getBindField()).set(new java.util.Date());
//                        dp.intoControl();
//                    }
//                    if (dp instanceof DataPairFieldTime) {
//                        ((BindTimeInterface)((DataPairFieldTime)dp).getBindField()).set(new java.util.Date());
//                        dp.intoControl();
//                    }
//                    if (dp instanceof DataPairFieldDateTime) {
//                        ((BindDateTimeInterface)((DataPairFieldDateTime)dp).getBindField()).set(new java.util.Date());
//                        dp.intoControl();
//                    }
//                    report_group.add(dp);
//                }
//                proceed = new JButton("OK");
//                report_group.add(proceed);
//                proceed.addActionListener(this);
//                dialog = new JDialog();
//                dialog.getContentPane().add(report_group);
//                dialog.pack();
//                dialog.setLocationRelativeTo(null);
//                dialog.setModal(true);
//                dialog.show();
//            } else {
//                buildReport();
//            }
        } catch ( Throwable exception) {
            exception.printStackTrace();
            throw new BindException(exception);
        }
    }
    
    private void buildReport()
    throws Exception {
//        binder.intoBindings();
//        bind_map.putAll(convertBindableToMap(bindable_properties));
//        try {
//            print = JasperManager.fillReport(report,bind_map,connection.getDBConnection());
//        } catch (Exception exception) {
//            Log.debug.out("REPORT EXECUTE FAILED",report.getQuery().getText());
//            throw exception;
//        }
    }
    
//    public JasperPrint getPrint() {
//        return print;
//    }
    
    public void actionPerformed(ActionEvent event) {
        try {
            buildReport();
            dialog.hide();
        } catch (Exception exception) {
            Log.debug.out(exception);
        }
    }
    
    private Hashtable convertBindableToMap(Bindable bindable)
    throws BindException{
        Hashtable map = new Hashtable();
        for (int i =0;i < bindable.getBindFields().length;i++) {
        	//TODO Must fix reports
//            map.put(
//                   bindable.getBindFields()[i].getName(),
//                   VectorJRParameter.correctType(bindable.getBindFields()[i])
//                    );
        }
        return map;
    }
    
//    public JFrame getComponent()
//    throws BindException {
//        try {
//            return new JasperViewer(print,false);
//        } catch (Exception exception) {
//            throw new BindException(exception);
//        }
//    }
    
//    public void print()  {
//        try {
//            JasperManager.printReport(print,false);
//        } catch (Exception exception) {
//            if (exception.getMessage().indexOf("Invalid page index range") != -1 ) {
//                JOptionPane.showMessageDialog(null,"No pages to print");
//            }
//            Log.debug.out(exception);
//        }
//    }
    
//    public boolean doesHavePages() {
//        return print.getPages().isEmpty();
//    }
    
    
//    public File toPdfFile(String destination)
//    throws BindException {
//        try {
//            JasperManager.printReportToPdfFile(print,destination);
//            return new File(destination);
//        } catch (Throwable throwable) {
//            throw new BindException(throwable);
//        }
//    }
    
//    public File toXlsFile(String destination)
//    throws BindException {
//        try {
//            JRXlsExporter exporter = new JRXlsExporter();
//            exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
//            exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destination );
//            exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
//            exporter.exportReport();
//            return new File(destination);
//        } catch (Throwable throwable) {
//            throw new BindException(throwable);
//        }
//    }
    
//    public File toHtmlFile(String destination)
//    throws BindException {
//        try {
//            JRHtmlExporter exporter = new JRHtmlExporter();
//            exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
//            exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destination );
//            exporter.exportReport();
//            return new File(destination);
//        } catch (Throwable throwable) {
//            throw new BindException(throwable);
//        }
//    }
    
//    public File toCsvFile(String destination)
//    throws BindException {
//        try {
//            JRCsvExporter exporter = new JRCsvExporter();
//            exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
//            exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destination );
//            exporter.exportReport();
//            return new File(destination);
//        } catch (Throwable throwable) {
//            throw new BindException(throwable);
//        }
//    }
    
}
